<template>
  <div id="manageQuestionView">
    <a-table
      :columns="columns"
      :data="dataList"
      :pagination="{
        pageSize: searchParams.pageSize,
        current: searchParams.current,
        total: total,
        showTotal: true,
      }"
      @page-change="onPageChange"
    >
      <template #optional="{ record }">
        <a-space>
          <a-button @click="doUpdate(record)" status="success">update</a-button>

          <a-button @click="doDelete(record)" status="danger">delete</a-button>
        </a-space>
      </template>
    </a-table>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch, watchEffect } from "vue";
import {
  Page_Question_,
  Question,
  QuestionControllerService,
} from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";

const router = useRouter();

const dataList = ref([]);

const total = ref();

const columns = [
  {
    title: "id",
    dataIndex: "id",
  },
  {
    title: "title",
    dataIndex: "title",
  },
  {
    title: "tags",
    dataIndex: "tags",
  },
  {
    title: "answer",
    dataIndex: "answer",
  },
  {
    title: "submitNum",
    dataIndex: "submitNum",
  },
  {
    title: "acceptedNum",
    dataIndex: "acceptedNum",
  },
  {
    title: "judgeConfig",
    dataIndex: "judgeConfig",
  },
  {
    title: "judgeCase",
    dataIndex: "judgeCase",
  },
  {
    title: "userId",
    dataIndex: "userId",
  },
  {
    title: "createTime",
    dataIndex: "createTime",
  },
  {
    title: "Optional",
    slotName: "optional",
  },
];

const searchParams = ref({
  pageSize: 10,
  current: 1,
});

const onPageChange = (page: number) => {
  searchParams.value = { ...searchParams.value, current: page };
};

const doUpdate = async (question: Question) => {
  message.success("update succeed!");
  router.push({
    path: "/update/question",
    query: {
      id: question.id,
    },
  });
  loadData();
};
const doDelete = async (question: Question) => {
  const res = await QuestionControllerService.deleteQuestionUsingPost({
    id: question.id,
  });
  if (res.code === 0) {
    message.success("delete succeed!");
    loadData();
  } else {
    message.error("delete failed!", res.message);
  }
};

const loadData = async () => {
  const res = await QuestionControllerService.listQuestionByPageUsingPost(
    searchParams.value
  );
  if (res.code === 0) {
    message.success("require dataList success!");
    dataList.value = res.data.records;
    total.value = res.data.total;
  } else {
    message.error("require dataList failed!", res.message);
  }
};

//当loadData函数中的变量发送变化的时候， 就会自动执行loadData
watchEffect(() => {
  loadData();
});

onMounted(() => {
  loadData();
});
</script>
